from flask import render_template, current_app, abort, g, request

from info import constants
from info.models import User, News
from info.other import other_blue
from info.utils.common import user_login_data


@other_blue.route('/<int:other_id>')
@user_login_data
def other(other_id):
    # 获取目标用户信息
    other_user = None
    try:
        other_user = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other_user:
        abort(404)

    if other_user.mobile.startswith('$'):
        abort(404)

    user_info = None
    is_followed = False
    if g.user:
        user = g.user
        if other_user.followers.filter(User.id == user.id).count() > 0:
            is_followed = True
        user_info = user.to_dict()

    # 新闻分页
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    news_li = []
    current_page = 1
    total_page = 1
    filters = [
        (News.user_id == other_user.id),
        (News.title.startswith('$$$isDeleted$$$') == False),
    ]

    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())

    data = {
        "user_info": user_info,
        "other_user": other_user.to_dict(),
        "is_followed": is_followed,
        "news_list": news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return render_template('news/other.html', data=data)

